package com.zgroup.services

import com.zgroup.domain.Bid;
import com.zgroup.domain.Estate;

class BidService extends DynamicService {

  boolean transactional = true

  // 中榜竞标

  def winBidList(pUser, pSize, pOffset) {
    return winBidList(pUser, pSize, pOffset, true)
  }

  def winBidList(pUser, pSize, pOffset, isPaginate) {
    String query = "from Bid as b where b.user=? and b.status = '10' and b.expired='0' and exists (select 1 from Estate as e where b.estate=e and b in (e.vipBid,e.firstBid,e.secondBid,e.thirdBid))"
    if (isPaginate) {
      return paginateList(query, [pUser], [max: pSize, offset: pOffset, sort: "dateCreated", order: "desc"], Bid)
    }
    return [
            "items": Bid.findAll(query + makeOrderBy("b", [sort: "dateCreated", order: "desc"]), [pUser], [max: pSize, offset: pOffset]),
            "count": 0
    ]
  }

  def bidList(pUser, pBidType, pSize, pOffset) {
    StringBuffer query = new StringBuffer()
    query.append("from Bid as b where b.user=? and b.status = '10' and b.expired='0' and exists (select 1 from Estate as e where b.estate=e ")
    if ("1" == pBidType) {
      query.append("and b =e.vipBid)")
    } else if ("2" == pBidType) {
      query.append("and b =e.firstBid)")
    } else if ("3" == pBidType) {
      query.append("and b =e.secondBid)")
    } else if ("4" == pBidType) {
      query.append("and b =e.thirdBid)")
    }

    return paginateList(query.toString(), [pUser], [max: pSize, offset: pOffset, sort: "dateCreated", order: "desc"], Bid)
  }

  //落榜竞标

  def failBidList(pUser, pSize, pOffset) {
    return failBidList(pUser, pSize, pOffset, true)
  }

  def failBidList(pUser, pSize, pOffset, isPaginate) {
    String query = "from Bid as b where b.user=? and b.status='20' and b.expired='0' "
    if (isPaginate) {
      return paginateList(query, [pUser], [max: pSize, offset: pOffset, sort: "dateCancelled", order: "desc"], Bid)
    }
    return [
            "items": Bid.findAll(query + makeOrderBy("b", [sort: "dateCancelled", order: "desc"]), [pUser], [max: pSize, offset: pOffset]),
            "count": 0
    ]
  }

  def championByPrice() {
    Bid.findAllByStatus("10", [max: 1, sort: "dayCost", order: "desc"])?.getAt(0)
  }

  def latestBid() {
    Bid.findAllByStatus("10", [max: 1, sort: "dateCreated", order: "desc"])?.getAt(0)
  }

  def listVipByEstate(pEstate, pSize) {
    Bid.findAllByTypeAndEstate("20", pEstate, [max: pSize, sort: "money", order: "desc"])
  }

  def listRankByEstate(pEstate, pSize) {
    Bid.findAllByTypeAndEstate("10", pEstate, [max: pSize, sort: "money", order: "desc"])
  }
}
